package com.qianfeng.day11.test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.UUID;

public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++){
            // 得到redis的连接
            Jedis jedis = RedisConnection.getJedis();
            // 监视num数据
            String watch = jedis.watch("num");
            // 获取当前优惠券已经被抢出的数量
            String num = jedis.get("num");
            int n = Integer.parseInt(num);
            if (n < 10){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Transaction transaction = jedis.multi();
                transaction.incr("num");
                List<Object> list = transaction.exec();
                String name = UUID.randomUUID().toString().replaceAll("-", "");
                if (list == null || list.size() == 0){
                    System.out.println(watch +  "==="+list+"----" + name + "手慢了，抢票失败");
                }else {
                    System.out.println(watch +  "==="+list+"----" + name + "抢到一张优惠券");
                }
            }
            jedis.close();
        }
    }


    public static void main(String[] args) {
        for (int i = 0; i < 5; i++){
            MyThread thread = new MyThread();
            thread.start();
        }
    }
}
